package com.dps.omc.shell;

import com.dps.omc.agent.queue.consumer.tasker.utils.LogThread;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;

/**
 * Created by lip on 2016-07-12.
 */
public class ShellClient {

    private static final Logger logger = LoggerFactory.getLogger(ShellClient.class);
    private String charset = "UTF-8"; // 设置编码格式
    private String user; // 用户名
    private String passwd; // 登录密码
    private String host; // 主机IP
    private JSch jsch;
    private Session session;
    private Channel channel = null;
    BufferedReader reader1 = null;
    BufferedReader reader2 = null;

    private WsSender wsSender;
    private PrintStream commander;
    private OutputStream inputstream_for_the_channel;
    private ByteArrayOutputStream outputStream;
    private ShellOutputTask shellOutputTask;

    public ShellClient(String user, String passwd, String host,WsSender wsSender) {
        this.user = user;
        this.passwd = passwd;
        this.host = host;
        this.wsSender = wsSender;
    }

    public void connect() throws JSchException {
        jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
    }

    public void init() throws Exception {
        jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        channel = session.openChannel("shell");
        ((ChannelShell) channel).setPtyType("xterm");

        inputstream_for_the_channel = channel.getOutputStream();
        commander = new PrintStream(inputstream_for_the_channel,true);

        outputStream = new ByteArrayOutputStream();
        channel.setOutputStream(outputStream, true);

        channel.connect();

        InputStream in2 = channel.getInputStream();
        reader2 = new BufferedReader(new InputStreamReader(in2,
                Charset.forName(charset)));

//        ShellOutputTask shellOutputTask = new ShellOutputTask(wsSender.getSession(),reader2);
        shellOutputTask = new ShellOutputTask(wsSender.getSession(),reader2);
        OutputTasks.putTask(wsSender.getSession().getId(),shellOutputTask);
        new Thread(new ShellOutputTask(wsSender.getSession(),reader2)).start();
    }



    public void exec1(String command) throws Exception {

        commander.println(command);
    }

    public void exec(String command)
    {
        try {
            channel = session.openChannel("exec");
        } catch (JSchException e) {
            e.printStackTrace();
        }
        BufferedReader reader1 = null;
        BufferedReader reader2 = null;
        StringBuffer sb = new StringBuffer();

        try {
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            channel.connect();
            InputStream in1 = channel.getExtInputStream();
            InputStream in2 = channel.getInputStream();
            reader1 = new BufferedReader(new InputStreamReader(in1,
                    Charset.forName(charset)));
            reader2 = new BufferedReader(new InputStreamReader(in2,
                    Charset.forName(charset)));
            String buf1 = null;
            String buf2 = null;

            new Thread(new LogThread(reader1,sb)).start();
            while ((buf2 = reader2.readLine()) != null) {
                sb.append(buf2);
                sb.append("\n");
                logger.info("read2:"+buf2);
            }

            wsSender.send(sb.toString());
            reader1.close();
            reader2.close();
            channel.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    public String execCmd(String command) {

        BufferedReader reader1 = null;
        BufferedReader reader2 = null;
        StringBuffer sb = new StringBuffer();

        try {
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            channel.connect();
            InputStream in1 = channel.getExtInputStream();
            InputStream in2 = channel.getInputStream();
            reader1 = new BufferedReader(new InputStreamReader(in1,
                    Charset.forName(charset)));
            reader2 = new BufferedReader(new InputStreamReader(in2,
                    Charset.forName(charset)));
            String buf1 = null;
            String buf2 = null;

            new Thread(new LogThread(reader1,sb)).start();
            while ((buf2 = reader2.readLine()) != null) {
                sb.append(buf2);
                sb.append("\n");
                logger.info("read2:"+buf2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public void close()
    {
        try {
//            reader1.close();
            reader2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        channel.disconnect();
        session.disconnect();
    }
}
